package com.stock.demo.function.market.view;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.stock.demo.R;
import com.stock.demo.adapter.MarketViewAdapter;
import com.stock.demo.adapter.MarketViewBodyAdapter;
import com.stock.demo.adapter.MarketViewFootAdapter;
import com.stock.demo.adapter.viewholder.StockViewHolder;
import com.stock.demo.framework.ui.fragment.BaseNetFragment;
import com.stock.demo.function.market.presenter.MarketPresenter;
import com.stock.demo.function.market.presenter.MarketPresenterImpl;
import com.stock.demo.model.MarketDetailBean;
import com.stock.demo.model.MarketIndexBean;
import com.stock.demo.model.MarketViewBody;
import com.stock.demo.model.MarketViewFoot;
import com.stock.demo.model.MarketViewHead;
import com.stock.demo.model.MarketViewType;
import com.stock.demo.util.SettingUtils;

import java.util.ArrayList;


/**
 * Created by XuZhaoyu on 2017/6/1.
 */

public class MarketFragment extends BaseNetFragment implements MarketView {

    private View mView;
    private RecyclerView mRvMarketList;

    private MarketPresenter mPresenter;
    private MarketViewAdapter mMarketAdapter;
    private ArrayList<MarketViewType> mAllMarketViewTypes;//所有数据的集合
    private Runnable mRunRefresh;
    private boolean mShouldRefresh;//判断是否需要刷新数据（是否停留在当前页面，不在当前页面就终止刷新）
    private boolean mShouldWait;//判断是否在时间间隔内（是否在刷新数据的间隔时间内，需要等待，如每3000MS发起一次网络请求数据）
    private boolean mIsViewCreated;//判断该页面是否已经绘制完毕

    @Override
    public View onCreateSuccessView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_market, container, false);
        return mView;
    }

    @Override
    public void onReload(View v) {

    }

    @Override
    public void initView() {
        mRvMarketList = (RecyclerView) mView.findViewById(R.id.rv_market_view_list);
        mIsViewCreated = true;
    }

    @Override
    public void initData() {
        initPresenter();
        mAllMarketViewTypes = new ArrayList<>();
        initMarketRecyclerView();
        mRunRefresh = new Runnable() {
            @Override
            public void run() {
                mShouldWait = false;
                mPresenter.getMarketInfo();
                System.out.println("market refresh");
            }
        };
        shouldRefresh(true);//第一次进入页面，让页面开始加载数据
    }

    //初始化Adapter
    private void initMarketRecyclerView() {
        mMarketAdapter = new MarketViewAdapter(mAllMarketViewTypes, R.layout.view_market_head, R.layout.view_market_body, R.layout.view_market_foot, new MarketViewAdapter.AdapterBindViewListener() {

            @Override
            public void bindHeadView(StockViewHolder holder, final int position) {
                final MarketViewType bean = mAllMarketViewTypes.get(position);
                if (bean != null && bean instanceof MarketViewHead) {
                    holder.itemView.setVisibility(View.VISIBLE);
                    MarketViewHead headBean = (MarketViewHead) bean;
                    LinearLayout llTitleContainer = (LinearLayout) holder.itemView.findViewById(R.id.ll_title_container);
                    final View llContainer = holder.itemView.findViewById(R.id.ll_market_list_head_container);
                    final ImageView ivArrow = (ImageView) holder.itemView.findViewById(R.id.iv_market_list_title);
                    TextView tvTitle = (TextView) holder.itemView.findViewById(R.id.tv_market_list_title);
                    llTitleContainer.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showOrHideMarketView(llContainer, ivArrow, position);
                        }
                    });
                    tvTitle.setText(headBean.mTitle);
                    //上证指数
                    TextView tvNameSh = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_name_sh);
                    TextView tvPointSh = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_point_sh);
                    TextView tvChangeSh = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_change_sh);
                    TextView tvChangePercentSh = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_change_percent_sh);
                    MarketIndexBean shIndex = headBean.mSHIndex;
                    if (shIndex != null) {
                        tvNameSh.setText(shIndex.mName);
                        if (shIndex.mChangePercent.startsWith("-")) {
                            tvPointSh.setTextColor(getResources().getColor(R.color.colorGreen));
                            tvChangeSh.setTextColor(getResources().getColor(R.color.colorGreen));
                            tvChangePercentSh.setTextColor(getResources().getColor(R.color.colorGreen));
                        } else if (!TextUtils.equals("0.00%", shIndex.mChangePercent)) {
                            tvPointSh.setTextColor(getResources().getColor(R.color.colorRed));
                            tvChangeSh.setTextColor(getResources().getColor(R.color.colorRed));
                            tvChangePercentSh.setTextColor(getResources().getColor(R.color.colorRed));
                        }
                        tvPointSh.setText(shIndex.mLastPoint);
                        tvChangeSh.setText(shIndex.mChange);
                        tvChangePercentSh.setText(shIndex.mChangePercent);
                    }
                    //深证成指
                    TextView tvNameSz = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_name_sz);
                    TextView tvPointSz = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_point_sz);
                    TextView tvChangeSz = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_change_sz);
                    TextView tvChangePercentSz = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_change_percent_sz);
                    MarketIndexBean szIndex = headBean.mSZIndex;
                    if (szIndex != null) {
                        tvNameSz.setText(szIndex.mName);
                        if (szIndex.mChangePercent.startsWith("-")) {
                            tvPointSz.setTextColor(getResources().getColor(R.color.colorGreen));
                            tvChangeSz.setTextColor(getResources().getColor(R.color.colorGreen));
                            tvChangePercentSz.setTextColor(getResources().getColor(R.color.colorGreen));
                        } else if (!TextUtils.equals("0.00%", szIndex.mChangePercent)) {
                            tvPointSz.setTextColor(getResources().getColor(R.color.colorRed));
                            tvChangeSz.setTextColor(getResources().getColor(R.color.colorRed));
                            tvChangePercentSz.setTextColor(getResources().getColor(R.color.colorRed));
                        }
                        tvPointSz.setText(szIndex.mLastPoint);
                        tvChangeSz.setText(szIndex.mChange);
                        tvChangePercentSz.setText(szIndex.mChangePercent);
                    }
                    //创业板指
                    TextView tvNameCy = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_name_cy);
                    TextView tvPointCy = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_point_cy);
                    TextView tvChangeCy = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_change_cy);
                    TextView tvChangePercentCy = (TextView) holder.itemView.findViewById(R.id.tv_market_list_head_change_percent_cy);
                    MarketIndexBean cyIndex = headBean.mCYIndex;
                    if (cyIndex != null) {
                        tvNameCy.setText(cyIndex.mName);
                        if (cyIndex.mChangePercent.startsWith("-")) {
                            tvPointCy.setTextColor(getResources().getColor(R.color.colorGreen));
                            tvChangeCy.setTextColor(getResources().getColor(R.color.colorGreen));
                            tvChangePercentCy.setTextColor(getResources().getColor(R.color.colorGreen));
                        } else if (!TextUtils.equals("0.00%", cyIndex.mChangePercent)) {
                            tvPointCy.setTextColor(getResources().getColor(R.color.colorRed));
                            tvChangeCy.setTextColor(getResources().getColor(R.color.colorRed));
                            tvChangePercentCy.setTextColor(getResources().getColor(R.color.colorRed));
                        }
                        tvPointCy.setText(cyIndex.mLastPoint);
                        tvChangeCy.setText(cyIndex.mChange);
                        tvChangePercentCy.setText(cyIndex.mChangePercent);
                    }
                } else {
                    holder.itemView.setVisibility(View.GONE);
                }
            }

            @Override
            public void bindBodyView(StockViewHolder holder, final int position) {
                MarketViewType bean = mAllMarketViewTypes.get(position);
                if (bean != null && bean instanceof MarketViewBody) {
                    holder.itemView.setVisibility(View.VISIBLE);
                    MarketViewBody hotBean = (MarketViewBody) bean;
                    if (hotBean.mMarketHotBeen != null && hotBean.mMarketHotBeen.size() > 0) {
                        LinearLayout llTitleContainer = (LinearLayout) holder.itemView.findViewById(R.id.ll_title_container);
                        final ImageView ivArrow = (ImageView) holder.itemView.findViewById(R.id.iv_market_list_title);
                        TextView tvTitle = (TextView) holder.itemView.findViewById(R.id.tv_market_list_title);
                        final RecyclerView rvBody = (RecyclerView) holder.itemView.findViewById(R.id.rv_market_list_body);
                        llTitleContainer.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showOrHideMarketView(rvBody, ivArrow, position);
                            }
                        });
                        tvTitle.setText(hotBean.mTitle);
                        rvBody.setLayoutManager(new GridLayoutManager(getContext(), 3));
                        rvBody.setAdapter(new MarketViewBodyAdapter(getContext(), hotBean.mMarketHotBeen));
                    }
                } else {
                    holder.itemView.setVisibility(View.GONE);
                }

            }

            @Override
            public void bindFootView(StockViewHolder holder, final int position) {
                MarketViewType bean = mAllMarketViewTypes.get(position);
                if (bean != null && bean instanceof MarketViewFoot) {
                    holder.itemView.setVisibility(View.VISIBLE);
                    MarketViewFoot footBean = (MarketViewFoot) bean;
                    if (footBean.mMarketFootBeen != null && footBean.mMarketFootBeen.size() > 0) {
                        LinearLayout llTitleContainer = (LinearLayout) holder.itemView.findViewById(R.id.ll_title_container);
                        final ImageView ivArrow = (ImageView) holder.itemView.findViewById(R.id.iv_market_list_title);
                        TextView tvTitle = (TextView) holder.itemView.findViewById(R.id.tv_market_list_title);
                        final RecyclerView rvFoot = (RecyclerView) holder.itemView.findViewById(R.id.rv_market_list_foot);
                        llTitleContainer.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showOrHideMarketView(rvFoot, ivArrow, position);
                            }
                        });
                        tvTitle.setText(footBean.mTitle);
                        rvFoot.setLayoutManager(new LinearLayoutManager(getContext()));
                        rvFoot.setAdapter(new MarketViewFootAdapter(getContext(), footBean.mMarketFootBeen));
                    }
                } else {
                    holder.itemView.setVisibility(View.GONE);
                }
            }
        });

        mRvMarketList.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvMarketList.setAdapter(mMarketAdapter);
    }

    private void showOrHideMarketView(View view, ImageView ivArrow, int position) {
        if (view.getVisibility() == View.VISIBLE) {
            view.setVisibility(View.GONE);
            ivArrow.setImageResource(R.mipmap.arrow_up);
        } else {
            view.setVisibility(View.VISIBLE);
            ivArrow.setImageResource(R.mipmap.arrow_down);
            mRvMarketList.scrollToPosition(position);
        }
    }

    @Override
    public void onGetMarketInfo(ArrayList<MarketViewType> marketViewTypes) {
        if (mAllMarketViewTypes != null && mAllMarketViewTypes.size() == 0) {
            onNetNext(marketViewTypes).setNetComplete();
        }
        if (mAllMarketViewTypes != null && marketViewTypes != null && marketViewTypes.size() > 0) {
            mAllMarketViewTypes.clear();
            mAllMarketViewTypes.addAll(marketViewTypes);
            mMarketAdapter.notifyDataSetChanged();
        }
        if ((!mShouldWait) && mShouldRefresh) {
            mShouldWait = true;
            mRvMarketList.postDelayed(mRunRefresh, SettingUtils.getRefreshSpeed());
        }
    }

    public void shouldRefresh(Boolean shouldRefresh) {
        if (mIsViewCreated) {
            mShouldRefresh = shouldRefresh;
            if (mShouldRefresh) {
                mPresenter.getMarketInfo();
                System.out.println("market refresh");
            }
        }
    }

    private void initPresenter() {
        if (mPresenter == null) {
            mPresenter = new MarketPresenterImpl(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mRvMarketList.removeCallbacks(mRunRefresh);
    }

    //空实现，无需操作
    @Override
    public void onGetStockDetail(MarketDetailBean detailBean) {

    }
}
